"""
产品相关视图
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view

from pecco_site.models import Product
from ..serializers.product import ProductListSerializer, ProductDetailSerializer
from ..filters import ProductFilter
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取产品列表', tags=['产品管理']),
    retrieve=extend_schema(summary='获取产品详情', tags=['产品管理']),
    create=extend_schema(summary='创建产品', tags=['产品管理']),
    update=extend_schema(summary='更新产品', tags=['产品管理']),
    partial_update=extend_schema(summary='部分更新产品', tags=['产品管理']),
    destroy=extend_schema(summary='删除产品', tags=['产品管理']),
)
class ProductViewSet(viewsets.ModelViewSet):
    """产品管理 ViewSet"""
    queryset = Product.objects.all().prefetch_related('categories', 'translations')
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = ProductFilter
    search_fields = ['translations__name', 'id']
    ordering_fields = ['sort_order', 'created_at', 'updated_at', 'id']
    ordering = ['sort_order', '-created_at']

    def get_serializer_class(self):
        if self.action == 'list':
            return ProductListSerializer
        return ProductDetailSerializer

    @extend_schema(
        summary='批量删除产品',
        tags=['产品管理'],
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'ids': {
                        'type': 'array',
                        'items': {'type': 'integer'},
                        'description': '要删除的产品 ID 列表'
                    }
                },
                'required': ['ids']
            }
        },
        responses={
            200: {
                'type': 'object',
                'properties': {
                    'message': {'type': 'string'},
                    'deleted_count': {'type': 'integer'}
                }
            }
        }
    )
    @action(detail=False, methods=['post'])
    def bulk_delete(self, request):
        """批量删除产品"""
        ids = request.data.get('ids', [])
        if not ids:
            return Response(
                {'error': '请提供要删除的产品 ID'},
                status=status.HTTP_400_BAD_REQUEST
            )

        deleted_count, _ = Product.objects.filter(id__in=ids).delete()
        return Response({
            'message': f'成功删除 {deleted_count} 个产品',
            'deleted_count': deleted_count
        })

    @extend_schema(
        summary='切换产品激活状态',
        tags=['产品管理'],
        responses={
            200: {
                'type': 'object',
                'properties': {
                    'is_active': {'type': 'boolean'}
                }
            }
        }
    )
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换产品激活状态"""
        product = self.get_object()
        product.is_active = not product.is_active
        product.save()
        return Response({'is_active': product.is_active})

    @extend_schema(
        summary='批量更新排序',
        tags=['产品管理'],
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'items': {
                        'type': 'array',
                        'items': {
                            'type': 'object',
                            'properties': {
                                'id': {'type': 'integer'},
                                'sort_order': {'type': 'integer'}
                            }
                        }
                    }
                }
            }
        }
    )
    @action(detail=False, methods=['post'])
    def bulk_update_sort(self, request):
        """批量更新排序"""
        items = request.data.get('items', [])
        for item in items:
            Product.objects.filter(id=item['id']).update(sort_order=item['sort_order'])
        return Response({'message': '排序更新成功'})

